<template>
    <div class="fly-header layui-bg-black">
        <div class="layui-container">
            <a class="fly-logo" href="/">
                <img src="../assets/imgs/newlogo.png" alt="layui">
            </a>
            <ul class="layui-nav fly-nav layui-hide-xs">
                <li class="layui-nav-item layui-this">
                    <a href="/"><i class="iconfont icon-jiaoliu"></i>交流</a>
                </li>
                <li class="layui-nav-item">
                    <a href="{:url('cases/index/index')}"><i class="iconfont icon-iconmingxinganli"></i>视频</a>
                </li>
                <li class="layui-nav-item">
                    <a href="http://www.100txy.com" target="_blank"><i class="iconfont icon-ui"></i>博客</a>
                </li>
            </ul>

            <ul class="layui-nav fly-nav-user">
                <!-- 未登入的状态 -->
                <!-- <template v-if="!userinfo.id"> -->
                <template v-if="user ==null || user == 'null' || user == ''">
                <li class="layui-nav-item">
                    <a class="iconfont icon-touxiang layui-hide-xs" href="{:url('user/index/login')}"></a>
                </li>
                <li class="layui-nav-item">
                    <a href="http://ssoserver.com:9096/authorize?client_id=test_client_3&response_type=code&scope=all&state=xyz&redirect_uri=http://localhost:8082">登入</a>
                </li>
                <li class="layui-nav-item">
                    <a href="/reg">注册</a>
                </li>
                <li class="layui-nav-item layui-hide-xs">
                    <a href="{:url('api/index/qqlogin')}" onclick="layer.msg('正在通过QQ登入', {icon:16, shade: 0.1, time:0})" title="QQ登入" class="iconfont icon-qq"></a>
                </li>
                <li class="layui-nav-item layui-hide-xs">
                    <a href="{:url('api/index/sinalogin')}" onclick="layer.msg('正在通过微博登入', {icon:16, shade: 0.1, time:0})" title="微博登入" class="iconfont icon-weibo"></a>
                </li>
                </template>
                <!-- 登入后的状态 -->
               <template v-else>
                <li class="layui-nav-item" @mouseover="mouseOver">
                    <a class="fly-nav-avatar" href="javascript:;">
                        <cite class="layui-hide-xs">{{user.nickname}}</cite>&nbsp;  
                        <i v-if="user.is_admin==1" class="iconfont icon-renzheng layui-hide-xs" title="认证信息：管理员"></i>
                        <i v-if="user.is_vip>0" class="layui-badge fly-badge-vip layui-hide-xs">VIP{{user.is_vip}}</i>
                        <img :src="user.head_img">
                    </a>
                    <dl class="layui-nav-child" :style="active"  @mouseleave="mouseLeave">
                        <dd><a href="/user/center"><i class="layui-icon">&#xe612;</i>用户中心</a></dd>
                        <dd><a href="/user/set"><i class="layui-icon">&#xe620;</i>基本设置</a></dd>
                        <dd><a href="{:url('user/index/message')}"><i class="iconfont icon-tongzhi" style="top: 4px;"></i>我的消息</a></dd>
                        <dd><a href="{:url('user/index/home',array('id'=>$Think.session.user.id))}"><i class="layui-icon" style="margin-left: 2px; font-size: 22px;">&#xe68e;</i>我的主页</a></dd>
                        <hr style="margin: 5px 0;">
                        <dd><a @click="logout" style="text-align: center;">退出</a></dd>
                    </dl>
                </li>
                </template>
            </ul>
        </div>
    </div>
</template>

<script>
import Cookies from 'js-cookie'
import request from '@/utils/request'
import { ElMessage,ElNotification } from 'element-plus'
import { mapState, mapMutations } from "vuex";
import { sendWebsocket, closeWebsocket } from '@/utils/websocket.js'
export default {
  name: 'Header',
  data() {
    return {
      userinfo: {}, //用户信息
      active: "",
      online: 0,
    };
  },
  mounted(){
   console.log("store.state:", this.$store.state)
    if(Cookies.get('app.token') != ""){
      console.log("有token")
        this.getUserInfo() //获取用户信息
    }else{
       console.log("没有token")
       this.$store.commit('setUser',null)
    }
   if(this.$store.state.tokeninfo === null){
     this.getGwToken() //获取网关token
   }
  },
  computed: {
      ...mapState(["user"])
  },
  created() {
    //获取登录信息
    // this.getLoginInfo()
    this.requstWs()
  },
  beforeUnmount () {
    // 页面销毁时关闭ws。因为有可能ws连接接收数据尚未完成，用户就跳转了页面
    // 在需要主动关闭ws的地方都可以调用该方法
    closeWebsocket()
  },
  methods: {
    ...mapMutations(["setUser","setTokeninfo"]),
    //获取登录信息
    getLoginInfo() {
      const params = {
        params: {
        }
      }
      request.get('/micro-bbs/v1/user/loginInfo', params).then((res) => {
        const { code, data } = res
        if (code === 200) {
          this.userinfo = data.userinfo
        }
      })
    },
    login(){
      this.$router.push("/login")
    },
    register(){
      this.$router.push("/reg")
    },
    logout(){
      const params = {
        params: {
        }
      }
      request.get('/micro-bbs/v1/user/logout', params).then((res) => {
        const { code } = res
        if (code === 200) {
          ElMessage({
              message: '退出成功！',
              type: 'success',
              offset: 200
           })
         localStorage.removeItem("token");
        //  localStorage.removeItem("user");
         this.$store.commit('setUser',null)
         Cookies.set('app.token', '', 'localhost')
        //  Cookies.set('app.user', '', 'localhost')
        this.$store.commit('setSignInfo',{"is_sign":false,"signInfo":{"days":0,"reward":0}})
         this.$router.push("/")
        }
      })
     
    },
    //获取用户信息-新oauth服务
    getUserInfo() {
      console.log("userId:",this.$store.getters.getUser.id)
      const params = {
        params: {
          user_id:this.$store.getters.getUser.id
        }
      }
      request.get('/micro-oauth2/oauth/user', params).then((res) => {
        console.log("res:",res)
        const { code, data } = res
        // this.notifySucceed(message);
        console.log("code:",code)
        if (code === 203) {
          //未授权
         this.$store.commit('setUser',null)
         Cookies.set('app.token', '', 'localhost')
        //  Cookies.set('app.user', '', 'localhost')
         this.$router.push("/")
        }
        if (code === 200) {
          // this.notifySucceed("本次验证码为："+data);
          //  ElMessage({
          //     message: 'Congrats, this is a success message.'+data,
          //     type: 'success',
          //     offset: 200
          //  })
           this.setUser(data.result)
        }
      })
    },
     //获取网关token
    getGwToken() {
      const params = {
          client_id:"azxdkku0mc45u5c09g05ob",
          client_secret:"dnsl5zaxf0n413e95m2xoq"
        }
      request.post('/http-oauth/oauth/api/v1/pos_token', JSON.stringify(params)).then((res) => {
        console.log("res:",res)
        const { status_code, payload } = res
        if (status_code === 0) {
           this.setTokeninfo(payload)
        }
      })
    },
    // 移入
    mouseOver() {
      this.active = "display:block;"
    },
    // 移出
    mouseLeave() {
      this.active = "";
    },
    // ws连接成功，后台返回的ws数据，组件要拿数据渲染页面等操作
    wsMessage (data) {
      const dataJson = data
      console.log("dataJson",dataJson)
      // 这里写拿到数据后的业务代码
      if(data.type == "message"){
          ElNotification({
            title: '浏览消息',
            message: dataJson,
            position: 'bottom-right',
          })
      }
      // this.online = dataJson.user_list.length
      this.$store.commit('setOnline',dataJson.user_list.length)
    },
    // ws连接失败，组件要执行的代码
    wsError () {
      // 比如取消页面的loading
    },
    requstWs () {
      // 防止用户多次连续点击发起请求，所以要先关闭上次的ws请求。
      closeWebsocket()
      // 跟后端协商，需要什么参数数据给后台
      const obj = {
        type: 'login',
        content: 'user'+this.uuid(8,16)
      }
      // 发起ws请求
      sendWebsocket('ws://localhost:8889/ws', obj, this.wsMessage, this.wsError)
    },

    uuid(len, radix) {
        var chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'.split('');
        var uuid = [], i;
        radix = radix || chars.length;
        if (len) {
            for (i = 0; i < len; i++) uuid[i] = chars[0 | Math.random() * radix];
        } else {
            var r;
            uuid[8] = uuid[13] = uuid[18] = uuid[23] = '-';
            uuid[14] = '4';
            for (i = 0; i < 36; i++) {
                if (!uuid[i]) {
                    r = 0 | Math.random() * 16;
                    uuid[i] = chars[(i == 19) ? (r & 0x3) | 0x8 : r];
                }
            }
        }
        return uuid.join('');
    }
  }
}
</script>
